<template>
    <div class="boxs">
        <el-card>
            <el-form :model="queryParams" ref="queryForm" :inline="true">
                <el-form-item label="起止时间">
                    <el-date-picker v-model="value1" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                        :start-placeholder="$t('table.start')" :end-placeholder="$t('table.end')" @change="timeChange">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button icon="el-icon-refresh" size="small"
                        @click="resetQuery">{{ $t('table.reset') }}</el-button>
                </el-form-item>
            </el-form>
            <div class="flex_between" style="margin-bottom: 20px;">
                <div>周续订率</div>
                <el-button type="warning" icon="el-icon-download" size="small"
                    @click="handleExport">{{ $t('table.export') }}</el-button>
            </div>
            <el-table :data="formattedData" border style="width: 100%" height="76vh">
                <el-table-column fixed="left" align="center" prop="base_date" label="基准日期" width="100">
                    <template slot-scope="scope">
                        {{ formatDate(scope.row.base_date) }}
                    </template>
                </el-table-column>
                <el-table-column fixed="left" align="center" prop="initial_count" label="基准续订数" width="100">
                    <template slot-scope="scope">
                        {{ scope.row.initial_count }}
                    </template>
                </el-table-column>
                <el-table-column align="center" width="150px" v-for="index in maxWeeks" :key="index"
                    :label="`第 ${index} 周 (${averageRates[index].toFixed(2)}%)`">
                    <template slot-scope="scope">
                        <div v-if="scope.row[`week_${index}_rate`] !== undefined">
                            <div>日期: {{ scope.row[`week_${index}_date`] }}</div>
                            <div>续费率: {{ (scope.row[`week_${index}_rate`] * 100).toFixed(2) }}%</div>
                            <div>续费数: {{ scope.row[`week_${index}_count`] }}</div>
                        </div>
                        <div v-else>无数据</div>
                    </template>
                </el-table-column>
            </el-table>
            <!-- <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.size"
                @pagination="getMore" />  -->
        </el-card>
    </div>
</template>
<script>
import { getWeeklyRenewalRatesByPk, getWeeklyRenewalRatesByPkNew } from "@/api/subscription";
import * as XLSX from "xlsx";

export default {
    name: "weeklyRates",
    data() {
        return {
            queryParams: {
                page: 1,
                size: 10,
                dateRange: {
                    start: "",
                    end: "",
                },
                state: "",
                package_name: "",
            },
            total: 0,
            loading: false,
            moreArr: [],
            form: {
                comment_type: "",
            },
            search: "",
            renewalRates: [],
            value1:''

        };
    },
    computed: {
        maxWeeks() {
            const weeksArray = this.renewalRates.map((item) => {
                const rates = item.rates ? JSON.parse(item.rates) : [];
                return rates.length;
            });
            return weeksArray.length > 0 ? Math.max(...weeksArray) : 0;
        },
        formattedData() {
            return this.renewalRates.map((item) => {
                const rates = item.rates ? JSON.parse(item.rates) : [];
                const formattedItem = {
                    base_date: item.base_date,
                    initial_count: item.initial_count,
                };
                rates.forEach((rate, index) => {
                    formattedItem[`week_${index + 1}_rate`] = rate.rate;
                    formattedItem[`week_${index + 1}_date`] = rate.week;
                    formattedItem[`week_${index + 1}_count`] = rate.count;
                });
                return formattedItem;
            });
        },
        averageRates() {
            const averages = {};
            for (let i = 1; i <= this.maxWeeks; i++) {
                let totalRate = 0;
                let count = 0;
                this.renewalRates.forEach(item => {
                    const rates = item.rates ? JSON.parse(item.rates) : [];
                    if (rates[i - 1] && rates[i - 1].rate !== undefined) {
                        totalRate += rates[i - 1].rate;
                        count++;
                    }
                });
                averages[i] = count > 0 ? (totalRate / count) * 100 : 0;
            }
            return averages;
        }
    },
    mounted() {
        const { pk } = this.$route.query;
        this.queryParams.pk = pk
        this.pk = pk
        // this.getWeeklyRenewalRatesByPk(pk)
        this.getWeeklyRenewalRatesByPkNew()

    },

    created() {
        // this.getMore();
    },
    methods: {
        timeChange() {
            this.queryParams.dateRange.start = this.value1[0];
            this.queryParams.dateRange.end = this.value1[1];
            this.getWeeklyRenewalRatesByPkNew();
        },
        resetQuery() {
            this.queryParams.dateRange.start = null;
            this.queryParams.dateRange.end = null;
            this.value1 = "";
            this.getWeeklyRenewalRatesByPkNew();
        },
        formatDate(date) {
            const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
            return new Date(date).toLocaleDateString('zh-CN', options);
        },
        async getWeeklyRenewalRatesByPkNew() {
            let { data } = await getWeeklyRenewalRatesByPkNew(this.queryParams);
            if (this.queryParams.pk === 'com.seamobitech.roku') {
                const cutoffDate = new Date('2024-11-15T00:00:00.000Z');
                data = data.filter(item => new Date(item.base_date) >= cutoffDate);
            }
            this.renewalRates = data
        },

        async handleExport() {
            this.loading = true;

            // 1. 定义基础表头
            const headers = {
                base_date: '基准日期',
                initial_count: '基准续订数',
            };

            // 2. 动态拼接每周的表头（保证列顺序，key 前缀有利于后续数据遍历）
            for (let i = 1; i <= this.maxWeeks; i++) {
                headers[`week_${i}_date`] = `第 ${i} 周日期`;
                headers[`week_${i}_count`] = `第 ${i} 周续费数`;
                headers[`week_${i}_rate`] = `第 ${i} 周续费率`;
            }

            // 3. 按 headers 顺序处理数据，格式化日期/百分比
            const transformedData = this.formattedData.map(item => {
                const newItem = {};
                for (const key in headers) {
                    if (key === 'base_date' && item[key]) {
                        // 日期统一转中国时区并格式化
                        const date = new Date(item[key]);
                        newItem[headers[key]] = date.toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai' });
                    } else if (key.includes('rate') && item[key] !== undefined) {
                        // 百分比格式化
                        newItem[headers[key]] = (item[key] * 100).toFixed(2) + '%';
                    } else {
                        // 其他都按原值，无则给“无数据”
                        newItem[headers[key]] = item[key] !== undefined ? item[key] : '无数据';
                    }
                }
                return newItem;
            });

            // 4. 利用 SheetJS 转为 CSV 字符串
            //    skipHeader: false 保留首行表头
            let csv = XLSX.utils.sheet_to_csv(
                XLSX.utils.json_to_sheet(transformedData),
                { FS: ",", RS: "\n", skipHeader: false }
            );
            // 5. 防止 Excel 打开乱码，加 BOM
            csv = "\uFEFF" + csv;

            // 6. 构建 Blob 并下载
            const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.download = "周续费留存报表.csv";
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(link.href);

            this.loading = false;
        }
,
        async getMore() {
            this.loading = true;
            let { data, total } = await extractPackageNames();
            this.loading = false;
            this.moreArr = data;
            this.total = total;
        },

        handleEdit(index, row) {
            this.$router.push({
                path: "/subscription/notificationList",
                query: { pk: row.pk },
            });
        },
        handles(index, row) {
            this.$router.push({
                path: "/subscription/statistics",
                query: { pk: row.pk },
            });
        },

    },
};
</script>
<style lang="scss" scoped>
.boxs {
    padding: 20px;
    
}

::v-deep.el-input.is-disabled .el-input__inner {
    color: #333 !important;
}

::v-deep.el-textarea.is-disabled .el-textarea__inner {
    color: #333 !important;
}

::v-deep .el-image {
    margin-right: 8px;
    border-radius: 4px;
    
}
</style>